package com.huanuo.internetofthings.service.resources;

import java.util.List;
import java.util.stream.Collectors;

import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.unicorn.framework.base.base.AbstractService;
import org.unicorn.framework.core.exception.PendingException;

import com.huanuo.internetofthings.bo.resources.Resources;
import com.huanuo.internetofthings.bo.roleResources.RoleResources;
import com.huanuo.internetofthings.bo.userRole.UserRole;
import com.huanuo.internetofthings.service.role.UserRoleService;

@Service
public class UserResourcesFacadeService extends AbstractService {
	
	@Autowired
	private UserRoleService userRoleService;
	
	@Autowired
	private ResourcesService resourcesService;
	
	@Autowired
    private RoleResourcesService roleResourcesService;
	/**
	 * 
	 * @param userRole
	 * @return
	 * @throws PendingException
	 */
	public List<Resources> getUserResourcesList(UserRole userRole) throws PendingException{
		List<Long> resourcesIdList=Lists.newArrayList(); 
		resourcesIdList.addAll(getResourcesIdsByRole(userRole));
		resourcesIdList.addAll(getResourcesIdsByUser(userRole));
		return resourcesService.selectListByIds(resourcesIdList);
	}
	/**
	 * 根据角色获取资源列表
	 * @param userRole
	 * @return
	 * @throws PendingException
	 */
	private List<Long> getResourcesIdsByRole(UserRole userRole) throws PendingException{
		List<UserRole> userRoleList=userRoleService.selectUserRoleList(userRole);
		List<Integer> roleIds=userRoleList.stream().map(ur->ur.getRoleId()).collect(Collectors.toList());
		List<RoleResources> roleResourceList=roleResourcesService.getRoleResourceListByRoleIds(roleIds);
		return roleResourceList.stream().map(roleResources->roleResources.getResourcesId()).collect(Collectors.toList());
	}
	/**
	 *  根据用户获取资源列表
	 * @param userRole
	 * @return
	 * @throws PendingException
	 */
	private List<Long> getResourcesIdsByUser(UserRole userRole) throws PendingException{
		List<UserRole> userRoleList=userRoleService.selectUserRoleList(userRole);
		List<Integer> roleIds=userRoleList.stream().map(ur->ur.getRoleId()).collect(Collectors.toList());
		List<RoleResources> roleResourceList=roleResourcesService.getRoleResourceListByRoleIds(roleIds);
		return roleResourceList.stream().map(roleResources->roleResources.getResourcesId()).collect(Collectors.toList());
	}
}